/**
 * 菜单模块服务文件
 */

const db = require('../db/menus');

/**
 * 添加菜单
 * @param {*} message 
 * @returns 
 */
const getAll = async ctx => {
    try {
        const data = await db.getAll();
        const top = data.filter(c => c.pid === 0).map(c => c.dataValues);  //顶级菜单
        const findChildren = arr => {
            for (const parent of arr) {
                const children = data.filter(c => c.pid === parent.id); //子菜单
                if (children.length) {
                    parent.children = children.map(c => c.dataValues);
                    findChildren(parent.children);
                }
            }
        }
        findChildren(top);
        ctx.body = {
            code: 1,
            data: top
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '菜单获取失败'
        }
    }
}

/**
 * 获取当前用户菜单
 */
const getCurrentUserMenus = async ctx => {
    try {
        const data = await db.getMenusByUserId(ctx.state.user.id);
        const menus = await db.getAll();
        const navigators = menus.filter(c => data.some(d => d.showParent && d.pid === c.id));  //所有的导航
        const categories = menus.filter(c => navigators.some(d => d.pid === c.id)); //所有的分类
        data.push(...navigators, ...categories);
        ctx.body = {
            code: 1,
            data
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '菜单获取失败'
        }
    }
}

/**
 * 根据角色ID获取权限
 * @param {*} ctx 
 */
const getRigthsByRoleId = async ctx => {
    try {
        const { id } = ctx.request.params;
        const data = await db.getMenuIdsByRoleId(id);
        ctx.body = {
            code: 1,
            data: data.map(c => c.menu_id)
        }
    } catch (error) {
        ctx.app.emit('error', error);
        ctx.body = {
            code: 0,
            msg: '权限获取失败'
        }
    }
}

module.exports = {
    getAll,
    getRigthsByRoleId,
    getCurrentUserMenus,
}